<template>
  <div>
    <div class="search">
      <input v-model="search" autofocus placeholder="搜索 IP 地址" />
    </div>

    <el-table :data="filterTableData" :height="tableHeight" stripe row-key="id" style="width: 100%">
      <el-table-column prop="ipaddress" label="IP 地址" width="180" />
      <el-table-column prop="hostname" label="主机名称" width="180" />
      <el-table-column prop="os_release" label="操作系统" width="220" />
      <el-table-column prop="desc" label="描述" width="220" />

      <el-table-column label="系统管理">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="shutdownOs(scope.row)">关机</el-button>
          <el-button link type="primary" size="small" @click="restartOs(scope.row)">重启</el-button>
        </template>
      </el-table-column>

      <el-table-column fixed="right" width="180">
        <template #header>
          <el-button type="primary" @click="state.addDialogVisible = true">添加服务</el-button>
        </template>
        <template #default="scope">
          <el-button link type="primary" plain size="small" @click="deleteSsh(scope.row)">删除</el-button>
          <el-button link type="primary" plain size="small" @click="showUpdateDialog(scope.row)">修改</el-button>
          <el-button link type="primary" size="small"
            @click="router.push('/machine/ssh/detail?r_id=' + scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination">
      <el-pagination layout="sizes, prev, pager, next" :total="paginationControl.total"
        v-model:current-page="paginationControl.current_page" v-model:page-size="paginationControl.page_size"
        :page-sizes="[10, 20, 30, 40, 50, 100]" />
    </div>

    <!-- 添加弹框 -->
    <div>
      <el-dialog v-model="state.addDialogVisible" title="添加 SSH 服务" destroy-on-close width="500"
        :close-on-click-modal="false">
        <el-form :model="addFormData" label-width="auto" style="max-width: 500px">
          <el-form-item label="IP 地址">
            <el-input v-model="addFormData.ipaddress" clearable />
          </el-form-item>
          <el-form-item label="用户">
            <el-input v-model="addFormData.user" clearable />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="addFormData.password" clearable />
          </el-form-item>
          <el-form-item label="端口">
            <el-input v-model="addFormData.port" type="number" clearable />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="addFormData.desc" clearable />
          </el-form-item>

          <div style="display: flex; justify-content: center">
            <el-button @click="state.addDialogVisible = false">退出</el-button>
            <el-button type="primary" @click="addSsh" :loading="state.loading">添加</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
    <!-- 更新弹框 -->
    <div>
      <el-dialog v-model="state.updateDialogVisible" title="更新 SSH 服务" destroy-on-close width="500"
        :close-on-click-modal="false">
        <el-form :model="updateFormData" label-width="auto" style="max-width: 600px">
          <el-form-item label="IP 地址">
            <el-input disabled v-model="updateFormData.ipaddress" />
          </el-form-item>
          <el-form-item label="用户">
            <el-input v-model="updateFormData.user" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="updateFormData.password" />
          </el-form-item>
          <el-form-item label="端口">
            <el-input v-model="updateFormData.port" type="number" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="updateFormData.desc" />
          </el-form-item>

          <div style="display: flex; justify-content: center">
            <el-button @click="state.updateDialogVisible = false">退出</el-button>
            <el-button type="primary" @click="updateSsh" :loading="state.loading">更新</el-button>
          </div>
        </el-form>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import * as sshApi from "@/api/ssh.js";
import { useRouter } from 'vue-router'

const router = useRouter();


let tableData = reactive({ data: [] });
const addFormData = reactive({ port: 22 });
const updateFormData = reactive({});

const state = reactive({
  addDialogVisible: false,
  updateDialogVisible: false,
  loading: false,
});

const paginationControl = reactive({
  total: 10,
  current_page: 0,
  page_size: 10,
});

let tableHeight = ref(100);

const search = ref("");
const filterTableData = computed(() =>
  tableData.data.filter(
    (data) =>
      !search.value ||
      data.ipaddress.toLowerCase().includes(search.value.toLowerCase())
  )
);

watch(
  [
    () => paginationControl.total,
    () => paginationControl.current_page,
    () => paginationControl.page_size,
  ],
  (newData, old) => {
    if (old[0] != newData[0] || old[1] != newData[1] || old[2] != newData[2]) {
      if (old[1] != 0) {
        getList(newData[1], newData[2]);
      }
    }
  }
);

function showUpdateDialog(row) {
  updateFormData.id = row.id;
  updateFormData.ipaddress = row.ipaddress;
  updateFormData.user = row.user;
  updateFormData.password = row.password;
  updateFormData.port = row.port;
  updateFormData.desc = row.desc;
  console.log(row)
  console.log(updateFormData)
  state.updateDialogVisible = true;
}

function addSsh() {
  state.loading = true;
  sshApi
    .addSsh(
      addFormData.ipaddress,
      addFormData.user,
      addFormData.password,
      addFormData.port,
      addFormData.desc
    )
    .then((resp) => {
      ElMessage.success("添加成功");
      state.addDialogVisible = false;
      getList(paginationControl.current_page, paginationControl.page_size);
    })
    .catch((err) => {
      ElMessage.error(err.response.data.title + ": " + err.response.data.description);
    })
    .finally(() => {
      state.loading = false;
    });
}

function getList(page, page_size) {
  sshApi
    .sshList(page, page_size)
    .then((resp) => {
      paginationControl.total = resp.data.total;
      paginationControl.current_page = resp.data.page;
      paginationControl.page_size = resp.data.page_size;
      console.log(resp.data.data);
      tableData.data = resp.data.data;
    })
    .catch((err) => {
      ElMessage.error("获取数据失败");
    });
}

function deleteSsh(row) {
  sshApi
    .deleteSsh(row.id)
    .then(() => {
      ElMessage.success("已删除");
      getList(paginationControl.current_page, paginationControl.page_size);
    })
    .catch((err) => {
      ElMessage.error("删除失败");
    });
}

function updateSsh() {
  state.loading = true;
  sshApi
    .updateSsh(
      updateFormData.id,
      updateFormData.user,
      updateFormData.password,
      updateFormData.port,
      updateFormData.desc
    )
    .then((resp) => {
      ElMessage.success("已更新");
      state.updateDialogVisible = false;
      getList(paginationControl.current_page, paginationControl.page_size);
    })
    .catch((err) => {
      ElMessage.error("更新失败");
    })
    .finally(() => {
      state.loading = false;
    });
}

function restartOs(row) {
  sshApi
    .restartOs(row.id)
    .then(() => {
      ElMessage.success("重启命令已发出");
    })
    .catch((err) => {
      ElMessage.error("发送命令失败, 请检查SSH服务是否正常");
    });
}

function shutdownOs(row) {
  sshApi
    .shutdownOs(row.id)
    .then(() => {
      ElMessage.success("关机机命令已发出");
    })
    .catch((err) => {
      ElMessage.error("发送命令失败, 请检查SSH服务是否正常");
    });
}

onMounted(() => {
  console.log(`the component is now mounted.`);
  getList();
  tableHeight = document.getElementById("app").offsetHeight - 60 - 140;
});
</script>

<style lang="less" scoped>
input {
  height: 50px;
  width: 100%;
  padding-left: 11px;
  border-top: none;
  border-left: none;
  border-right: none;
  border-bottom-width: 1px;
  border-bottom-color: #ccc;
  line-height: 50px;
  border-radius: 0;
  outline: none;
}

.pagination {
  margin-top: 10px;
  display: flex;
  justify-content: center;
}
</style>
